package com.music.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.okserver.download.DownloadInfo;
import com.lzy.okserver.download.DownloadManager;
import com.lzy.okserver.download.DownloadService;
import com.lzy.okserver.listener.DownloadListener;
import com.lzy.okserver.task.ExecutorWithListener;
import com.music.R;
import com.music.entity.online.OnlineMusicInfo;
import com.music.utils.CacheUtil;
import com.music.ui.view.NumberProgressBar;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dingfeng on 2016/9/23.
 */
public class DownloadingFragment extends FragmentBase
        implements View.OnClickListener, ExecutorWithListener.OnAllTaskEndListener {

    private Context mContext;
    private Button pauseAll;
    private Button startAll;
    private ListView mListView;
    private TextView emptyView;

    private List<DownloadInfo> allTask;
    private List<DownloadInfo> downloadingTask = new ArrayList<>();
    private MyAdapter adapter;
    private DownloadManager downloadManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_downloading, container, false);
        mContext = getContext();
        downloadManager = DownloadService.getDownloadManager();
        downloadManager.getThreadPool().getExecutor().addOnAllTaskEndListener(this);
        initView(view);
        loadData();
        return view;
    }

    private void initView(View view) {
        pauseAll = (Button) view.findViewById(R.id.pauseAll) ;
        startAll = (Button) view.findViewById(R.id.startAll) ;
        pauseAll.setOnClickListener(this);
        startAll.setOnClickListener(this);
        mListView = (ListView) view.findViewById(R.id.listView);
        emptyView = (TextView) view.findViewById(R.id.emptyView);
        mListView.setEmptyView(emptyView);
    }

    private void loadData() {
        allTask = downloadManager.getAllTask();
        for (DownloadInfo info : allTask) {
            if (info.getState() != DownloadManager.FINISH) {
                downloadingTask.add(info);
            }
        }
        adapter = new MyAdapter();
        mListView.setAdapter(adapter);
    }

    @Override
    public void onAllTaskEnd() {
//        for (DownloadInfo downloadInfo : allTask) {
//            if (downloadInfo.getState() != DownloadManager.FINISH) {
//                Toast.makeText(mContext, "所有下载线程结束，部分下载未完成", Toast.LENGTH_SHORT).show();
//                return;
//            }
//        }
//        Toast.makeText(mContext, "所有下载任务完成", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResume() {
        super.onResume();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //记得移除，否者会回调多次
        downloadManager.getThreadPool().getExecutor().removeOnAllTaskEndListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pauseAll:// 全部暂停
                downloadManager.pauseAllTask();
                break;
            case R.id.startAll:// 全部开始
                downloadManager.startAllTask();
                break;
        }
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return downloadingTask.size();
        }

        @Override
        public DownloadInfo getItem(int position) {
            return downloadingTask.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            DownloadInfo downloadInfo = getItem(position);
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(getContext(), R.layout.item_download_manager, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.refresh(downloadInfo);

            //对于非进度更新的ui放在这里，对于实时更新的进度ui，放在holder中
            OnlineMusicInfo onlineMusicInfo = (OnlineMusicInfo) CacheUtil.getInstance(mContext).getObject(downloadInfo.getUrl());
            if (onlineMusicInfo != null) {
                Glide.with(mContext).load(onlineMusicInfo.getPicSmall()).error(R.drawable.default_cover).into(holder.icon);
                holder.name.setText(onlineMusicInfo.getTitle());
            } else {
                holder.name.setText(downloadInfo.getFileName());
            }

            holder.remove.setOnClickListener(holder);

            DownloadListener downloadListener = new MyDownloadListener();
            downloadListener.setUserTag(holder);
            downloadInfo.setListener(downloadListener);
            return convertView;
        }
    }

    private class ViewHolder implements View.OnClickListener {
        private DownloadInfo downloadInfo;
        private ImageView icon;
        private TextView name;
        private TextView downloadSize;
        private TextView netSpeed;
        private NumberProgressBar pbProgress;
        private Button remove;

        public ViewHolder(View convertView) {
            icon = (ImageView) convertView.findViewById(R.id.icon);
            name = (TextView) convertView.findViewById(R.id.name);
            downloadSize = (TextView) convertView.findViewById(R.id.downloadSize);
            netSpeed = (TextView) convertView.findViewById(R.id.netSpeed);
            pbProgress = (NumberProgressBar) convertView.findViewById(R.id.pbProgress);
            remove = (Button) convertView.findViewById(R.id.remove);
        }

        public void refresh(DownloadInfo downloadInfo) {
            this.downloadInfo = downloadInfo;
            refresh();
        }

        //对于实时更新的进度ui，放在这里，例如进度的显示，而图片加载等，不要放在这，会不停的重复回调
        //也会导致内存泄漏
        private void refresh() {
            String downloadLength = Formatter.formatFileSize(getContext(), downloadInfo.getDownloadLength());
            String totalLength = Formatter.formatFileSize(getContext(), downloadInfo.getTotalLength());
            downloadSize.setText(downloadLength + "/" + totalLength);
            if (downloadInfo.getState() == DownloadManager.NONE) {
                netSpeed.setText("停止");
            } else if (downloadInfo.getState() == DownloadManager.PAUSE) {
                netSpeed.setText("暂停中");
            } else if (downloadInfo.getState() == DownloadManager.ERROR) {
                netSpeed.setText("下载出错");
            } else if (downloadInfo.getState() == DownloadManager.WAITING) {
                netSpeed.setText("等待中");
            } else if (downloadInfo.getState() == DownloadManager.FINISH) {
                netSpeed.setText("下载完成");
            } else if (downloadInfo.getState() == DownloadManager.DOWNLOADING) {
                String networkSpeed = Formatter.formatFileSize(mContext, downloadInfo.getNetworkSpeed());
                netSpeed.setText(networkSpeed + "/s");
            }
            pbProgress.setMax((int) downloadInfo.getTotalLength());
            pbProgress.setProgress((int) downloadInfo.getDownloadLength());
        }

        @Override
        public void onClick(View v) {
            if (v.getId() == remove.getId()) {
                downloadManager.removeTask(downloadInfo.getUrl());
                downloadingTask.remove(downloadInfo);
                adapter.notifyDataSetChanged();
            }
        }
    }

    private class MyDownloadListener extends DownloadListener {

        @Override
        public void onProgress(DownloadInfo downloadInfo) {
            if (getUserTag() == null) return;
            ViewHolder holder = (ViewHolder) getUserTag();
            holder.refresh();  //这里不能使用传递进来的 DownloadInfo，否者会出现条目错乱的问题
        }

        @Override
        public void onFinish(DownloadInfo downloadInfo) {
            Toast.makeText(mContext, "下载完成:" + downloadInfo.getFileName(), Toast.LENGTH_SHORT).show();
            downloadingTask.remove(downloadInfo);
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onError(DownloadInfo downloadInfo, String errorMsg, Exception e) {
            if (errorMsg != null) Toast.makeText(mContext, errorMsg, Toast.LENGTH_SHORT).show();
        }
    }


}
